/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.service.dao;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.joda.time.DateTime;
import org.tnmk.common.util.Filter;
import org.tnmk.worktime.service.dao.entry.SessionEntry;
import org.tnmk.worktime.service.filter.MonthTimeFilter;
import org.tnmk.worktime.service.filter.PreviousTimeFilter;
import org.tnmk.worktime.service.filter.WeekTimeFilter;

/**
 * Handle insert/update/delete/select WorkSession from storage
 *
 * @author tnmkhoi
 */
public class SessionDao extends BaseDao<SessionEntry> {
  private static final SessionDao instance = new SessionDao();
  public static SessionDao getInstance(){
    return instance;
  }
  
  public void addOrUpdateSessionAndSpends(SessionEntry session){
    //clear old spend of old session
    SessionEntry oldSession = find(session.getId());
    if (oldSession != null){
      
    }
    
    //save session and its spends (insert/update)
    super.addOrUpdate(session);
    
  }
  
  private SessionDao() {
    super(SessionEntry.class);
  }

  public SessionEntry findPreviousSession(SessionEntry session) {
    SessionEntry rs = null;
    DateTime inTime = session.getInTime();
    DateTime maxPreviousTime = null;
    Collection<SessionEntry> all = super.getAll();
    for (SessionEntry isession : all) {
      DateTime itime = isession.getInTime();
      if (itime.isBefore(inTime)){
        if (maxPreviousTime == null || itime.isAfter(maxPreviousTime)){
          maxPreviousTime = itime;
          rs = isession;
        }
      }
    }
    return rs;
  }
  
  public List<SessionEntry> findPreviousSessions(SessionEntry session) {
    PreviousTimeFilter filter = new PreviousTimeFilter(session.getInTime());
    return findSessions(filter);
  }

  /**
   * @param session
   * @return The list of sessions which are in the same week of @session. This list includes @session.
   */
  public List<SessionEntry> findWeekSessions(SessionEntry session) {
    WeekTimeFilter filter = new WeekTimeFilter(session.getInTime());
    return findSessions(filter);
  }

  public List<SessionEntry> findMonthSessions(SessionEntry session) {
    MonthTimeFilter filter = new MonthTimeFilter(session.getInTime());
    return findSessions(filter);
  }

  List<SessionEntry> findSessions(Filter<DateTime> filter) {
    List<SessionEntry> rs = new ArrayList<>();
    Collection<SessionEntry> all = super.getAll();
    for (SessionEntry isession : all) {
      if (filter.accept(isession.getInTime())) {
        rs.add(isession);
      }
    }
    return rs;
  }
}
